package com.smarthome.core.propertymanager.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.smarthome.base.service.ShDoorService;
import com.smarthome.base.service.ShPropertyFeeService;
import com.smarthome.core.housemanager.ResidenceFeeService;
import com.smarthome.core.propertymanager.PropertyMoneyService;
import com.smarthome.domain.bean.ShDoor;
import com.smarthome.domain.bean.ShPropertyFee;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;

@Service("propertyMoneyService")
public class PropertyMoneyServiceImpl implements PropertyMoneyService {

	@Resource
	private ShPropertyFeeService shPropertyFeeService;
	@Resource
	private ResidenceFeeService residenceFeeService;
	@Resource
	private ShDoorService shDoorService;

	@Override
	public DataGrid dataGrid(PageHelper page, Long numId) {
		return shPropertyFeeService.queryShPropertyFees(page, numId);
	}

	@Override
	public String doMoney(Long residenId) {
		String msg = "该小区下所有设置了物业费率的住户的物业费已计算成功！";
		// 1.取出该小区下的所有业主（门牌集合）
		// 2.依次计算门牌对应业主的物业费，物业费 = 业主房屋面积*物业费系数 +其他费用
		List<ShDoor> doors = shDoorService.queryDoorsByRedanceId(residenId);
		PageHelper page = new PageHelper();
		page.setPage(1);
		page.setRows(1);
		for (int i = 0; i < doors.size(); i++) {
			// 查询对应门牌下的物业费记录，取id最大的一条记录，如果没有记录则从useDate开始计算
			ShDoor door = doors.get(i);
			DataGrid data = shPropertyFeeService.queryShPropertyFees(page,
					door.getId());
			if (door.getBaseFee() == null || door.getOtherFee() == null) {
				continue;
			}
			List<String> months;
			if (data.getTotal() != null && data.getTotal() > 0) {
				ShPropertyFee tyFee = (ShPropertyFee) data.getRows().get(0);
				months = getMonths(addMonth(tyFee.getMonth(), 1));
			} else {
				months = getMonths(toMonth(door.getUseDate()));
			}
			insertFee(months, door);
		}
		return msg;
	}

	/**
	 * 获取需要生成物业费的月份集合
	 * 
	 * @param month
	 * @return
	 */
	private List<String> getMonths(String month) {
		List<String> months = new ArrayList<String>();
		int i = 0;
		while (compareMonth(addMonth(month, i))) {
			months.add(addMonth(month, i));
			i++;
		}
		return months;
	}

	private boolean compareMonth(String month) {
		boolean flag = true;
		String a = "yyyy年MM月";
		SimpleDateFormat sdf = new SimpleDateFormat(a);
		String nowMonth = sdf.format(new Date());
		if (nowMonth.equals(month)) {
			flag = false;
		}
		return flag;
	}

	private String toMonth(Date date) {
		String month = "";
		if (date != null) {
			String a = "yyyy年MM月";
			SimpleDateFormat sdf = new SimpleDateFormat(a);
			month = sdf.format(date);
		}
		return month;
	}

	private String addMonth(String month, int i) {
		String add = "";
		String a = "yyyy年MM月";
		SimpleDateFormat sdf = new SimpleDateFormat(a);
		try {
			Date date = sdf.parse(month);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.MONTH, i);
			add = sdf.format(cal.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return add;
	}

	private void insertFee(List<String> months, ShDoor door) {
		if (months.size() > 0) {
			// 物业费 = 业主房屋面积*物业费系数 +其他费用
			Long amount = (long) (Double.parseDouble(door.getSpace())
					* door.getBaseFee() + door.getOtherFee());
			for (int i = 0; i < months.size(); i++) {
				ShPropertyFee fee = new ShPropertyFee();
				fee.setDoorId(door.getId());
				fee.setSpace(door.getSpace());
				fee.setAmount(amount);
				fee.setStatus(2);
				fee.setMonth(months.get(i));
				shPropertyFeeService.insert(fee);
			}
		}
	}

	@Override
	public List<ShPropertyFee> getByDoorIdAndMonth(ShPropertyFee fee) {
		return shPropertyFeeService.getByDoorIdAndYear(fee);
	}

	@Override
	public List<ShPropertyFee> getByDoorIdAndBetweenMonth(ShPropertyFee fee) {
		return shPropertyFeeService.getByDoorIdAndMonth(fee);
	}

	@Override
	public void updateStatusById(Long id) {
		ShPropertyFee fee = shPropertyFeeService.selectEntryById(id);
		fee.setStatus(1);
		shPropertyFeeService.saveOrUpdate(fee);
	}

	@Override
	public ShPropertyFee getFeeById(Long id) {
		return shPropertyFeeService.selectEntryById(id);
	}

}
